package com.xiaoxi.exam.job;

import cn.xinzhili.xutils.core.ErrorCode;
import cn.xinzhili.xutils.core.FailureException;
import com.aliyuncs.exceptions.ClientException;
import com.xiaoxi.exam.consts.Const;
import com.xiaoxi.exam.utils.SmsUtil;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Data
@Slf4j
@AllArgsConstructor
@NoArgsConstructor
public class ToeflRegisterJob {

  private String tel;
  private boolean notUrgent;

  public boolean register(String userName, String password, boolean needSend) {
    Process process = null;
    BufferedReader in = null;
    try {
      System.out.println("start register  ...");
      String[] arg = new String[]{"python", "C:\\Login.py", userName,
          password};
      process = Runtime.getRuntime().exec(arg);
      in = new BufferedReader(
          new InputStreamReader(process.getInputStream(), "GBK"));
      String result = in.readLine();
      in.close();
      process.waitFor();
      boolean success = result.startsWith("1");
      if (needSend) {
        if (success) {
          log.info("return message is : {}", result);
          Integer money = Integer.valueOf(result.split("-")[1]);
          if (notUrgent) {
            if (money < Integer.valueOf(Const.FEE_MAP.get("cost"))) {
              String cost = "{\"money\":\"" + Const.FEE_MAP.get("cost") + "\"}";
              log.info("send sms str:{}", cost);
              sendMoneyNotEnoughSms(tel, "SMS_152851684", cost);
            }
          } else {
            if (money < Integer
                .valueOf(Const.FEE_MAP.get("cost") + Integer.valueOf(Const.FEE_MAP.get("extra")))) {
              String jsonStr = "{\"money\":\"" + Const.FEE_MAP.get("urgent") + "\",\"extra\":\"" +
                  Const.FEE_MAP.get("extra") + "\"}";
              log.info("send urgent sms str:{}", jsonStr);
              sendUrgentMoneyNotEnoughSms(tel, "SMS_152856592", jsonStr);
            }
          }
        }
      }
      return success;
    } catch (Exception e) {
      e.printStackTrace();
      throw new FailureException(ErrorCode.REQUEST_FAILED);
    } finally {
      in = null;
    }
  }

  private static void sendUrgentMoneyNotEnoughSms(String tel, String template, String jsonStr) {
    try {
      SmsUtil.sendSms(tel, template, jsonStr);
    } catch (ClientException e) {
      e.printStackTrace();
    }
  }

  private static void sendMoneyNotEnoughSms(String tel, String template, String jsonStr) {
    try {
      SmsUtil.sendSms(tel, template, jsonStr);
    } catch (ClientException e) {
      e.printStackTrace();
    }
  }
}

